package com.lxz.shardingjdbcdemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxz.shardingjdbcdemo.dao.OrderMapper;
import com.lxz.shardingjdbcdemo.model.Order;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/orders")
public class OrderController {

    @Resource
    private OrderMapper orderMapper;

    /**
     * 插入订单数据，测试分片
     */
    @PostMapping("/add")
    public String addOrders() {
        Random random = new Random();
        for (int i = 1; i <= 10; i++) {
            Order order = new Order();
            int userId = random.nextInt(1000) + 1; // 随机生成用户ID
            order.setUserId(userId);
            order.setOrderNo("ORD_" + System.currentTimeMillis() + "_" + i);
            order.setAmount(new BigDecimal(random.nextInt(1000)));
            // orderId将由ShardingSphere的SNOWFLAKE算法自动生成
            orderMapper.insert(order);
        }
        return "Successfully added 10 orders.";
    }

    /**
     * 查询所有订单，测试数据聚合
     */
    @GetMapping("/all")
    public List<Order> getAllOrders() {
        return orderMapper.selectList(null);
    }

    /**
     * 根据 orderId 查询订单，测试带分片键的查询
     */
    @GetMapping("/{orderId}")
    public Order getOrderByOrderId(@PathVariable Long orderId) {
        return orderMapper.selectById(orderId);
    }
    
    /**
     * 根据 userId 查询订单，测试不带分片键的查询
     */
    @GetMapping("/user/{userId}")
    public List<Order> getOrdersByUserId(@PathVariable Integer userId) {
        // 使用QueryWrapper查询
        return orderMapper.selectList(new QueryWrapper<Order>().eq("user_id", userId));
    }

    /**
     *  根据orderId列表进行查询
     **/
    @GetMapping("/list")
    public List<Order> getOrdersByOrderIds(@RequestParam List<Long> orderIds) {
        return orderMapper.selectBatchIds(orderIds);
    }
}